#include "api/apiclient.h"
#include "apiresources.h"
#include "common/serialization.h"
#include "httpclient.h"
#include "resultvo.h"
#include <iostream>

void ApiClient::test()
{
	std::cout << "This is cxi_api test." << std::endl;
	std::cout << "准备测试HTTP请求：" << std::endl;
	HttpClient httpClient("http://192.168.6.27:8888/corexapi/admin/platform/getSystemDate");
	std::string response;
	const bool res = httpClient.post("", response);
	std::cout << "测试结果：" << res << std::endl;
	std::cout << "代码：" << httpClient.httpCode() << std::endl;
	if (res)
	{
		std::cout << "返回结果：" << response << std::endl;
	}
	else
	{
		std::cout << "信息：" << httpClient.error() << std::endl;
	}
}

//获取服务器时间最大时间间隔（毫秒）
constexpr int MAX_TIMESTAMP = 6000;
//获取服务器时间的本地时间戳
static QDateTime localDateTime = QDateTime::fromString("1970-01-01");
//暂存的服务器当前时间
static QDateTime remoteDateTime;
QDateTime ApiClient::systemDateTime()
{
	const QDateTime now = QDateTime::currentDateTime();
	if (const qint64 mSecs = now.msecsTo(localDateTime); mSecs >= MAX_TIMESTAMP || mSecs <= 0)
	{
		/*时间戳大于间隔，重新获取服务器时间*/
		HttpClient httpClient(ApiResources::getUrl(API_SYSDATE));
		if (std::string response; httpClient.post("", response))
		{
			ResultVo data;
			if (const bool rst = serialization::deserializeJson(response, data); rst && data.flag == 0)
			{
				//转换结果
				remoteDateTime = QDateTime::fromString(data.resultObj, "yyyy-MM-ddTHH:mm:ss.zzz");
			}
		}
		//设置当前时间戳
		localDateTime = now;
	}

	return remoteDateTime;
}